//
//  ComposeViewController.swift
//  Stauts
//
//  Created by Kylin on 16/3/24.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    // MARK:-  控件属性
    @IBOutlet weak var customTextView: ComposeTextView!
    @IBOutlet weak var toolBar: UIToolbar!
    
    // MARK:- 约束属性
    @IBOutlet weak var toolBarButtomCons: NSLayoutConstraint!
    

    // MARK:-  懒加载属性
    private lazy var titleView : ComposeTitleView = ComposeTitleView()
    private lazy var picturePickerVc : PicturePickerViewController =
    PicturePickerViewController(collectionViewLayout:PicturePickerCollectionViewLayout ())
    private lazy var emoticonVc : EmoticonViewController = EmoticonViewController {[weak self] (emoticon) -> () in
        // 1.插入表情
        self?.customTextView.insertEmoticon(emoticon)
        // 2.动画调用文字发生改变的代理方法
        self?.textViewDidChange(self!.customTextView)
    }
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()

        // 1:设置导航栏
        setupNavgationBar()
        
        // 2:监听键盘的弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
         // 3.将照片选择的View,添加到发布控制器的View
        setupPicturePickerView()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 一打开textView就弹出键盘
        customTextView.becomeFirstResponder()
    }

    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
// MARK:- 设置UI相关的
extension ComposeViewController {
   // 设置导航栏
    private func setupNavgationBar() {
        // 1:设置左侧的Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(ComposeViewController.cancelItemClick))
        
        // 2:设置右侧的Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: #selector(ComposeViewController.sendItemClick))
        navigationItem.rightBarButtonItem?.enabled = false
        // 3:设置标题
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 36)
        navigationItem.titleView = titleView
    }
    
    /// 将照片选 择器的View添加到发布控制器的View
    
    private func setupPicturePickerView () {
        
        // 1:添加子控制器
        // 因为picturePickerVC需要弹出其它控制器,所以必须加入发由控制器的子控制器里面
        self.addChildViewController(picturePickerVc)
        self.view.insertSubview(picturePickerVc.view , belowSubview: toolBar)
        
        // 2:设置位置和尺寸
        picturePickerVc.view.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(0)
            make.bottom.equalTo(0)
            make.trailing.equalTo(0)
            make.height.equalTo(0)
        }
       
    }
}

// MARK:- 事件监听函数
extension ComposeViewController {
    // 取消按钮的点击
    @objc private func cancelItemClick () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 发送按钮的点击
    @objc private func sendItemClick () {
       
        // 1:显示进度
        SVProgressHUD.show()
        
        // 2:获取发布的内容
        let statusText = customTextView.getEmoticonString()

        // 3:取出用户选中的图片
        let image = picturePickerVc.images.first
        
        // 4:发布微博
       NetworTools.shareManager.sendstatus(statusText, image: image) { (isSuccess) -> () in
        if !isSuccess {
            SVProgressHUD.showErrorWithStatus("发送失败")
            return
          }
            self.dismissViewControllerAnimated(true, completion: nil)
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    /// 监听键盘的弹出
    @objc private func keyboardWillChangeFrame (note : NSNotification) {
        // 1.取出键盘最终frame和键盘弹出的时间
        let endFrameValue = note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let endFrame = endFrameValue.CGRectValue()
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        // 2:计算工具栏距离底部的约束
        let bottomCons = UIScreen.mainScreen().bounds.height - endFrame.origin.y
        
        // 3:改变工具栏距离底部的约束
        toolBarButtomCons.constant = bottomCons
        
        // 4:执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            // 中断之前的动画,执行下一次动画
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 8)!)
            self.view.layoutIfNeeded()
        }
        
    }
    /// 监听照片选择按钮的点击
    @IBAction func picturePickerBtnClick() {
        // 1:退出键盘
        customTextView.resignFirstResponder()
        
        // 2:重新设置picturePicker的高度约束
        picturePickerVc.view.snp_remakeConstraints { (make) -> Void in
            make.leading.equalTo(0)
            make.bottom.equalTo(0)
            make.trailing.equalTo(0)
            make.height.equalTo(self.view.snp_height).multipliedBy(0.65)
        }
        
        // 3:执行动画
        UIView.animateWithDuration(0.4) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    /// 表情键盘的切换
    @IBAction func emoticonBtnClick() {
        // 1:退出键盘
        customTextView.resignFirstResponder()
        // 2:切换键盘
        customTextView.inputView = customTextView.inputView == nil ? emoticonVc.view : nil
        // 3:切换键盘
        customTextView.becomeFirstResponder()
    }
   
}
// MARK:- 实现textView的代理方法
extension ComposeViewController : UITextViewDelegate {
    
    // 当文字发生改变的时侯会调用该方法
    func textViewDidChange(textView: UITextView) {
        customTextView.placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // 2.当用户开始拖拽scrollView时会执行该方法
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        customTextView.resignFirstResponder()
    }
    
}
